//
//  BDMessageListViewController.m
//  iOS_beboy
//
//  Created by wen on 2018/1/29.
//  Copyright © 2018年 com.8xiong. All rights reserved.
//

#import "BDMessageListViewController.h"
#import "BDUserModel.h"
#import "PopoverView.h"
#import "BDFMDBTool.h"
#import "BDMessageListTableViewCell.h"
#import <JMessage/JMessage.h>
#import "BDChatViewController.h"
#import "BDScanViewController.h"
#import "BDFriendsListViewController.h"
#import "BDAddFriendViewController.h"
#import "BDGroupChooseViewController.h"

@interface BDMessageListViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    NSInteger _unreadCount;
}
@property (nonatomic, strong) UIButton *avatarButton;
@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UILabel *applyCountView;
@property (nonatomic, strong) NSMutableArray *datasource;

@property (nonatomic, strong) UIView *guestView;
@property (nonatomic, strong) UIView *backView;

@end

@implementation BDMessageListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = ASLocalizedString(@"消息");
    self.view.backgroundColor = kBDColorGray;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UITableView alloc] init];
    [self.view addSubview:_tableView];
    
    [self layoutViews];
    [self bindRAC];
    
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTabBarHeight - kBDTopHeight)];
    _backView.backgroundColor = [UIColor clearColor];
    _backView.hidden = YES;
    [self.view addSubview:_backView];
    
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.image = [UIImage imageNamed:@"wuxinxi(1)"];
    imageView.size = CGSizeMake(kBDScreenWidth, 240);
    imageView.left = 0;
    imageView.bottom = self.backView.height - kBDTopHeight;
    [self.backView addSubview:imageView];
    
    UILabel *backLabel = [[UILabel alloc] init];
    backLabel.text = ASLocalizedString(@"目前还没有收到任何信息~~~");
    backLabel.textColor = KBDColorBlue;
    backLabel.textAlignment = NSTextAlignmentCenter;
    backLabel.size = CGSizeMake(200, 20);
    backLabel.font = [UIFont systemFontOfSize:15];
    backLabel.top = _backView.top + 90 - 64;
    backLabel.left = (kBDScreenWidth - 200) / 2;
    [self.backView addSubview:backLabel];
    
    UIButton *beginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    beginButton.top = backLabel.bottom + 20;
    beginButton.size = CGSizeMake(102, 35);
    beginButton.centerX = self.backView.centerX;
    [beginButton setTitle:ASLocalizedString(@"开始闲聊")forState:UIControlStateNormal];
    [beginButton setTitleColor:KBDColorBlue forState:UIControlStateNormal];
    beginButton.titleLabel.font = [UIFont systemFontOfSize:15];
    beginButton.layer.cornerRadius = 5;
    beginButton.layer.borderColor = KBDColorBlue.CGColor;
    beginButton.layer.borderWidth = 1;
    beginButton.backgroundColor = [UIColor clearColor];
    [self.backView addSubview:beginButton];
    
    [[beginButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [BDUserModel judgeCurrentUserWithNormalBlock:^{
            BDFriendsListViewController *fridentListVC = [[BDFriendsListViewController alloc]init];
            fridentListVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:fridentListVC animated:YES];
        }];
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self requestDatasource];
}

- (void)layoutViews{
    UIBarButtonItem *backBarButton=[[UIBarButtonItem alloc]initWithCustomView:self.avatarButton];
    self.navigationItem.leftBarButtonItem = backBarButton;
    
    UIBarButtonItem *rightItem=[[UIBarButtonItem alloc]initWithCustomView:self.rightButton];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)bindRAC{
    [[self.avatarButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [BDUserModel judgeCurrentUserWithNormalBlock:^{
            BDFriendsListViewController *fridentListVC = [[BDFriendsListViewController alloc]init];
            fridentListVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:fridentListVC animated:YES];
        }];
    }];
    
    [[self.rightButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [BDUserModel judgeCurrentUserWithNormalBlock:^{
            PopoverAction *addFriAction = [PopoverAction actionWithTitle:ASLocalizedString(@"添加好友")handler:^(PopoverAction *action) {
                BDAddFriendViewController *newFriendVC = [[BDAddFriendViewController alloc] init];
                newFriendVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:newFriendVC animated:YES];
            }];
            PopoverAction *qunliaoAction = [PopoverAction actionWithTitle:ASLocalizedString(@"发起群聊")handler:^(PopoverAction *action) {
                BDGroupChooseViewController *groupChooseVC = [[BDGroupChooseViewController alloc] init];
                [self presentViewController:[[UINavigationController alloc] initWithRootViewController:groupChooseVC] animated:YES completion:nil];
            }];
            PopoverAction *saoyisaoAction = [PopoverAction actionWithTitle:ASLocalizedString(@"扫一扫")handler:^(PopoverAction *action) {
                BDScanViewController *scanVC = [[BDScanViewController alloc] init];
                scanVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:scanVC animated:YES];
            }];
            PopoverView *popoverView = [PopoverView popoverView];
            [popoverView showToView:self.rightButton withActions:@[addFriAction, qunliaoAction, saoyisaoAction]];//, qunliaoAction, myQunliaoAction
        }];
    }];
}

- (void)requestDatasource{
    [JMSGConversation allConversations:^(id resultObject, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error == nil) {
                _datasource = [self sortConversation:resultObject];
                _unreadCount = 0;
                for (NSInteger i=0; i < [_datasource count]; i++) {
                    JMSGConversation *conversation = [_datasource objectAtIndex:i];
                    _unreadCount = _unreadCount + [conversation.unreadCount integerValue];
                }
                [self saveBadge:_unreadCount];
            } else {
                _datasource = nil;
            }
            [self.tableView reloadData];
            
            if (_datasource.count == 0) {
                _backView.hidden = NO;
            }else{
                _backView.hidden = YES;
            }
        });
    }];
}

#pragma mark --排序conversation
- (NSMutableArray *)sortConversation:(NSMutableArray *)conversationArr {
    NSSortDescriptor *firstDescriptor = [[NSSortDescriptor alloc] initWithKey:@"latestMessage.timestamp" ascending:NO];
    
    NSArray *sortDescriptors = [NSArray arrayWithObjects:firstDescriptor, nil];
    
    NSArray *sortedArray = [conversationArr sortedArrayUsingDescriptors:sortDescriptors];
    
    return [NSMutableArray arrayWithArray:sortedArray];
    
    //    NSArray *sortResultArr = [conversationArr sortedArrayUsingFunction:sortType context:nil];
    //    return [NSMutableArray arrayWithArray:sortResultArr];
}

- (void)saveBadge:(NSInteger)badge {
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%zd",badge] forKey:@"kbadge"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_datasource count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"JCHATConversationListCell";
    BDMessageListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[BDMessageListTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
    }
    JMSGConversation *conversation = [_datasource objectAtIndex:indexPath.row];
    [cell setCellDataWithConversation:conversation];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 65;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BDChatViewController *chatVC = [[BDChatViewController alloc] init];
    chatVC.hidesBottomBarWhenPushed = YES;
    chatVC.conversation = _datasource[indexPath.row];
    [self.navigationController pushViewController:chatVC animated:YES];
}

//头像按钮
- (UIButton *)avatarButton{
    if (!_avatarButton) {
        self.avatarButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
        [_avatarButton setBackgroundImage:[UIImage imageNamed:@"message_haoyou"] forState:UIControlStateNormal];
        [_avatarButton addSubview:self.applyCountView];
        self.applyCountView.centerX = _avatarButton.width;
        self.applyCountView.centerY = 0;
    }
    return _avatarButton;
}

- (UILabel *)applyCountView{
    if (!_applyCountView) {
        self.applyCountView = [[UILabel alloc] init];
        _applyCountView.backgroundColor = [UIColor redColor];
        _applyCountView.textColor = [UIColor whiteColor];
        _applyCountView.font = [UIFont systemFontOfSize:8];
        _applyCountView.size = CGSizeMake(16, 16);
        _applyCountView.textAlignment = NSTextAlignmentCenter;
        //        _applyCountView.text = @"1";
        _applyCountView.layer.masksToBounds = YES;
        _applyCountView.layer.cornerRadius = 8;
    }
    return _applyCountView;
}

-(UIButton *)rightButton{
    if (!_rightButton) {
        self.rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
        [_rightButton setBackgroundImage:[UIImage imageNamed:@"xiala"] forState:UIControlStateNormal];
    }
    return _rightButton;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
